/**
 * Copyright (C) 2016-2019 DSpot Sp. z o.o
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dspot.declex.actions;

import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import com.dspot.declex.annotation.action.ActionFor;
import com.dspot.declex.annotation.action.FormattedExpression;

import org.ohosannotations.annotations.RootContext;

@ActionFor(value = "Toast", timeConsuming = false)
public class ToastActionHolder {


    String text;
    int res;

    @RootContext
    Context context;

    Runnable Shown;

    // Toast.LENGTH_LONG为3500ms
    int duration = 3500;

    void init(@FormattedExpression String text) {
        this.text = text;
    }

    void init(int res) {
        this.res = res;
    }

    void build(Runnable Shown) {
        this.Shown = Shown;
    }

    void execute() {
        if (context == null) return;

        Runnable callToast = new Runnable() {

            @Override
            public void run() {
                if (text != null) {
                    ToastDialog toastDialog = new ToastDialog(context);
                    toastDialog.setText(text);
                    toastDialog.setDuration(duration);
                    toastDialog.show();

                } else if (res != 0) {
                    ToastDialog toastDialog = new ToastDialog(context);
                    toastDialog.setText(context.getString(res));
                    toastDialog.setDuration(duration);
                    toastDialog.show();
                } else {
                    ToastDialog toastDialog = new ToastDialog(context);
                    toastDialog.setText("Toast Error: Toast message was not provided");
                    toastDialog.setDuration(duration);
                    toastDialog.show();
                }
                if (Shown != null) Shown.run();
            }
        };

        //Thread save
        if (EventRunner.getMainEventRunner() == EventRunner.getMainEventRunner()) {
            callToast.run();
        } else {
            EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());
            handler.postTask(callToast);
        }

    }

    public ToastActionHolder shortLength() {
        duration = 500;
        return this;
    }

    public ToastActionHolder longLength() {
        duration = 1000;
        return this;
    }

}